package com.penglecode.netty3.example1;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class EchoClientHandler extends SimpleChannelHandler {

	private static final Logger logger = LoggerFactory.getLogger(EchoClientHandler.class);
	
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		logger.error("client internal error!", e.getCause());
	}

	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		logger.debug("[client] channel = {}", e.getChannel());
		logger.debug("[client] message = {}", MessageUtils.getMessage(e.getMessage()));
		logger.debug("[client] remoteAddress = {}", e.getRemoteAddress());
		e.getChannel().close();
	}

	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		logger.debug("[client] channel = {}", e.getChannel());
		logger.debug("[client] state = {}", e.getState());
		logger.debug("[client] a channel closed!");
	}

	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		logger.debug("[client] channel = {}", e.getChannel());
		logger.debug("[client] state = {}", e.getState());
		logger.debug("[client] client connected to the server!");
		String messageText = "你好，服务器！我是客户端.";
		logger.debug("[client] send message to the server = {}", messageText);
		MessageUtils.sendMessage(e, messageText);
	}

	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) throws Exception {
		logger.debug("[client] channel = {}", e.getChannel());
		logger.debug("[client] state = {}", e.getState());
		logger.debug("[client] a channel disconnected!");
	}
	
}
